package com.platform.service;

import com.platform.dao.ApiTokenMapper;
import com.platform.entity.TokenEntity;
import com.platform.entity.UserVo;
import com.platform.util.CheckSumBuilder;
import com.platform.utils.CharUtil;
import io.rong.RongCloud;
import io.rong.methods.user.User;
import io.rong.models.Result;
import io.rong.models.response.TokenResult;
import io.rong.models.user.UserModel;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.NameValuePair;

import java.util.ArrayList;
import java.util.List;


@Service
public class TokenService {
    @Autowired
    private ApiTokenMapper tokenDao;
    /**
     * 此处替换成您的appKey
     */
    private static final String appKey = "bmdehs6pbr2js";
    /**
     * 此处替换成您的appSecret
     */
    private static final String appSecret = "naVuStGEpO";
    /**
     * 自定义api地址
     */
    private static final String api = "http://api.cn.ronghub.com";

    public TokenEntity queryByUserId(Long userId) {
        return tokenDao.queryByUserId(userId);
    }

    public TokenEntity queryByToken(String token) {
        return tokenDao.queryByToken(token);
    }

    public void save(TokenEntity token) {
        tokenDao.save(token);
    }

    public void update(TokenEntity token) {
        tokenDao.update(token);
    }

    public Map<String, Object> createToken(UserVo userVo) throws Exception {
        //判断是否生成过token
        TokenEntity tokenEntity = queryByUserId(userVo.getId());

        //当前时间
        Date now = new Date();
        /**
         * API 文档: http://rongcloud.github.io/server-sdk-nodejs/docs/v1/user/user.html#register
         *
         * 注册用户，生成用户在融云的唯一身份标识 Token
         */
        String token = "";
        if (tokenEntity == null) {
            tokenEntity = new TokenEntity();
            tokenEntity.setUserId(userVo.getId());
            tokenEntity.setUpdateTime(now);

            JSONObject obj = getToken("https://api.netease.im/nimserver/user/create.action", userVo.getMobile());
            String code = obj.getString("code");

            if (code != null && code.equals("414")) {
                JSONObject objupData = getToken("https://api.netease.im/nimserver/user/refreshToken.action", userVo.getMobile());
                String code2 = objupData.getString("code");
                JSONObject  info = objupData.getJSONObject("info");
                token = info.getString("token");
                if (code2 != null && code2.equals("200")) {
                    tokenEntity.setToken(token);
                }
            }

            if (code != null && code.equals("200")) {
                JSONObject info = obj.getJSONObject("info");
                token = info.getString("token");
                tokenEntity.setToken(token);
            }

            save(tokenEntity);
        } else {
            JSONObject objupData = getToken("https://api.netease.im/nimserver/user/refreshToken.action", userVo.getMobile());
            String code = objupData.getString("code");
            JSONObject info = objupData.getJSONObject("info");
            token = info.getString("token");
            if (code != null && code.equals("200")) {
                tokenEntity.setToken(token);
                tokenEntity.setUpdateTime(now);
                update(tokenEntity);
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return map;
    }

    public JSONObject getToken(String url, String accid) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        String appKey = "88dbf5b9ec957818be39f778ba290ad5";
        String appSecret = "54b1e8eeca05";
        String nonce = "10240000";
        String token = "";
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        /**
         * 参考 计算CheckSum的java代码
         */
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);
        /**
         * 设置请求的header
         */
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        /**
         * 设置请求的参数
         */
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid", accid));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

        /**
         * 执行请求
         */
        HttpResponse response = httpClient.execute(httpPost);

        String res = EntityUtils.toString(response.getEntity(), "utf-8");
        JSONObject obj = JSONObject.fromObject(res);
        return obj;
    }


    public static void main(String[] args) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = "https://api.netease.im/nimserver/user/create.action";
        HttpPost httpPost = new HttpPost(url);

        String appKey = "88dbf5b9ec957818be39f778ba290ad5";
        String appSecret = "54b1e8eeca05";
        String nonce = "12345";
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        /**
         * 参考 计算CheckSum的java代码
         */
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);
        /**
         * 设置请求的header
         */
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        /**
         * 设置请求的参数
         */
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid", "17798903668"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

        /**
         * 执行请求
         */
        HttpResponse response = httpClient.execute(httpPost);

        String res = EntityUtils.toString(response.getEntity(), "utf-8");
        JSONObject obj = JSONObject.fromObject(res);
        String code = obj.getString("code");
        if (code != null && code.equals("200")) {
            JSONObject info = obj.getJSONObject("info");
            String token = info.getString("token");
            System.out.println(token);
        }
        if (code != null && code.equals("414")) {

        }
        System.out.println(res);

    }

}
